package com.education.service.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.education.common.utils.FormUtils;
import com.education.common.utils.MD5;
import com.education.dto.MemberDto;
import com.education.exception.OnlineEducationException;
import com.education.helper.JwtHelper;
import com.education.helper.JwtInfo;
import com.education.result.ResultCodeEnum;
import com.education.service.ucenter.entity.Member;
import com.education.service.ucenter.entity.form.LoginForm;
import com.education.service.ucenter.entity.form.RegisterForm;
import com.education.service.ucenter.mapper.MemberMapper;
import com.education.service.ucenter.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author Lance
 * @since 2020-07-04
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 会员注册
     * @param registerForm
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(RegisterForm registerForm) {
        String nickname = registerForm.getNickname();
        String mobile = registerForm.getMobile();
        String password = registerForm.getPassword();
        String code = registerForm.getCode();

        //校验参数
        if (StringUtils.isEmpty(nickname)){
            throw new OnlineEducationException(ResultCodeEnum.NULL_NICK_NAME);
        }if (StringUtils.isEmpty(mobile)){
            throw new OnlineEducationException(ResultCodeEnum.NULL_PHONE_CODE);
        }if (!FormUtils.isMobile(mobile)){
            throw new OnlineEducationException(ResultCodeEnum.LOGIN_PHONE_ERROR);
        }if (StringUtils.isEmpty(code)){
            throw new OnlineEducationException(ResultCodeEnum.NULL_VERIFY_CODE);
        }if (StringUtils.isEmpty(password)){
            throw new OnlineEducationException(ResultCodeEnum.NULL_PASSWORD);
        }if (!FormUtils.isPassWord(password)){
            throw new OnlineEducationException(ResultCodeEnum.NULL_PASSWORD_CODE);
        }

        // 校验验证码
        String key = "phoneCode::" + mobile;
        String checkCode = (String)redisTemplate.opsForValue().get(key);
        if(!code.equals(checkCode)){
            throw new OnlineEducationException(ResultCodeEnum.CODE_ERROR);
        }

        //是否被注册
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        Integer count = baseMapper.selectCount(queryWrapper);
        if(count > 0){
            throw new OnlineEducationException(ResultCodeEnum.REGISTER_MOBLE_ERROR);
        }

        //注册
        Member member = new Member();
        member.setNickname(nickname);
        member.setMobile(mobile);
        // 密码进行加密
        member.setPassword(MD5.encrypt(password));
        // 会员是否被禁用
        member.setDisabled(false);
        member.setAvatar("https://guli-file-helen.oss-cn-beijing.aliyuncs.com/avatar/default.jpg");
        baseMapper.insert(member);
    }

    /**
     * 用户登录
     * @param loginForm
     * @return
     */
    @Override
    public String login(LoginForm loginForm) {
        String mobile = loginForm.getMobile();
        String password = loginForm.getPassword();

        //校验参数
        if (StringUtils.isEmpty(mobile)){
            throw new OnlineEducationException(ResultCodeEnum.NULL_PHONE_CODE);
        }if (!FormUtils.isMobile(mobile)){
            throw new OnlineEducationException(ResultCodeEnum.LOGIN_PHONE_ERROR);
        }if (StringUtils.isEmpty(password)){
            throw new OnlineEducationException(ResultCodeEnum.NULL_PASSWORD_ERROR);
        }

        //校验手机号
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        Member member = baseMapper.selectOne(queryWrapper);
        if (member == null) {
            throw new OnlineEducationException(ResultCodeEnum.LOGIN_MOBILE_ERROR);
        }

        //校验密码
        if (!MD5.encrypt(password).equals(member.getPassword())) {
            throw new OnlineEducationException(ResultCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //检验用户是否被禁用
        if (member.getDisabled()) {
            throw new OnlineEducationException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setId(member.getId());
        jwtInfo.setNickname(member.getNickname());
        jwtInfo.setAvatar(member.getAvatar());
        String token = JwtHelper.createToken(jwtInfo);

        return token;
    }

    /**
     * 根据openid返回用户信息
     * @param openid
     * @return
     */
    @Override
    public Member getByOpenid(String openid) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据会员ID查询会员信息
     * @param memberId
     * @return
     */
    @Override
    public MemberDto getMemberDtoById(String memberId) {
        Member member = baseMapper.selectById(memberId);
        MemberDto memberDto = new MemberDto();
        BeanUtils.copyProperties(member, memberDto);
        return memberDto;
    }

    /**
     * 根据日期统计用户注册数量
     * @param day
     * @return
     */
    @Override
    public Integer countRegisterNum(String day) {
        return baseMapper.selectRegisterNumByDay(day);
    }
}
